package com.bionic.banking.dao.connection;

import com.bionic.banking.auth.manager.Config;
import com.bionic.banking.dao.classes.BankAccountDaoImp;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.apache.log4j.Priority;

class ConnectionPool {

    private static final Logger logger = LoggerLoader.getLogger(ConnectionPool.class);
    
    private static String JNDI_NAME = "java:comp/env";
    private static String DATASOURCE;
    private static DataSource dsObj;
    private static Connection connection;
    static ConnectionPool instance = null;    
    
    public static synchronized ConnectionPool getInstance() throws NamingException {
        if (instance == null) {
            instance = new ConnectionPool();
        }
        return instance;
    }

    private ConnectionPool() throws NamingException {
        DATASOURCE = Config.getInstance().getProperty(Config.DATASOURCE);
        init();
    }

    private void init() throws NamingException {
        Context initContext = new InitialContext();
        Context envContext = (Context) initContext.lookup(JNDI_NAME);
        dsObj = (DataSource) envContext.lookup(DATASOURCE);
        //or dsObj = org.apache.tomcat.jdbc.pool.DataSourceFactory.createDataSource(dsProperties);      
    }

    public synchronized Connection getConnection() throws SQLException, NamingException {
        connection = dsObj.getConnection();
        return dsObj.getConnection();
    }

    public void freeConnection() throws SQLException{
        try {
            if (connection != null) {
                connection.close();
            }            
        } catch (SQLException ex) {
            logger.error(ex.getMessage());
            throw new SQLException(ex.getMessage());
        }
    }

    public void freeConnection(Connection conn) throws SQLException{
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException ex) {
             logger.error(ex.getMessage());
            throw new SQLException(ex.getMessage());
        }
    }
}
